$(function () {
	// 获取枚举类
	$.get(baseURL + 'storeMaterials/storematerialinOut/getEnum', function(r){
		vm.e.whetherEnum = r.whetherEnum;
		vm.e.stockMaterialIoTypeEnum = r.stockMaterialIoTypeEnum;
		vm.e.directionEnum = r.directionEnum;
		vm.e.storeMaterialOutInStatusEnum = r.storeMaterialOutInStatusEnum;
		vm.e.financePaymentStatusEnum = r.financePaymentStatusEnum;
		vm.e.storeMaterialInStatusEnum = r.storeMaterialInStatusEnum;

	});

	// 获取耗材分类树信息
	$.get(baseURL + "purchase/storepurchaseapply/getEnumList/", function(r){
		vm.materialCategoryList = r.materialCategoryTree;
		vm.e.materialUnitEnum = r.materialUnitEnum;
		vm.e.materialSupplier = r.materialSupplier;
		vm.e.purchaseApplyStatusEnum = r.purchaseApplyStatusEnum;
	});


	$("#jqGrid").jqGrid({
		url: baseURL + 'storeMaterials/storematerialinOut/list',
		datatype: "json",
		colModel: [
			{ label: '操作', name: 'outId' , align: 'center', width: 80,
				formatter:function(value, options, row){
					var actions = [];
					if(row.status === 1){
						actions.push('<a href="javascript:void(0);"  onclick="vm.auditOrRejectData={id:'+row.outId+',operate:1,msg:\'确认审核通过？\'}; vm.auditDialogVisible = true">审核</a>') ;
						actions.push('|') ;
						actions.push('<a href="javascript:void(0);"  onclick="vm.auditOrRejectData={id:'+row.outId+',operate:0,msg:\'确认驳回？\'}; vm.auditDialogVisible = true">驳回</a>') ;
						return actions.join('  ');
					}else{
						actions.push('<span>------</span>') ;
						return actions.join('  ');
					}

				}
			},
			{label: '出库自增id',name:'outId',index: 'out_id',hidden:true},
			{ label: '出库仓库名称', name: 'stockName', index: 'stock_name', width: 80,align:'center'},
			{ label: '单据号', name: 'outNo', index: 'out_no', width: 80 ,align:'center' },
			{ label: '总金额', name: 'totalMoney', index: 'total_money', width: 40, align:'right'},
			{ label: '是否含税', name: 'tax', width: 80, align:'center',
				formatter: function (value, options, row) {
					var valueText = "";
					$.each(vm.e.whetherEnum, function (index, module) {
						if (module.id == value) {
							valueText = module.describe;
							return false;
						}
					});
					return valueText;
				}
			},
			{ label: '库存交易类型', name: 'type', index: 'type', width: 80, align:'center',
				formatter: function (value, options, row) {
					var valueText = "";
					$.each(vm.e.stockMaterialIoTypeEnum, function (index, module) {
						if (module.id == value) {
							valueText = module.describe;
							return false;
						}
					});
					return valueText;
				}
			},
			{ label: '单据状态', name: 'status', index: 'status', width: 80, align:'center',
				formatter: function (value, options, row) {
					var valueText = "";
					$.each(vm.e.storeMaterialOutInStatusEnum, function (index, module) {
						if (module.id == value) {
							valueText = module.describe;
							return false;
						}
					});
					return valueText;
				}
			},
			{ label: '备注', name: 'remark', index: 'remark', width: 80},
			{ label: '创建人', name: 'createName', index: 'create_name', width: 80, align:'center'},
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 80, align:'center'},
			{ label: '审核人', name: 'checkName', index: 'check_name', width: 80, align:'center'},
			{ label: '审核时间', name: 'checkTime', index: 'check_time', width: 80, align:'center'},
			{ label: '详情', name: 'detail', index: 'detail', align:'center' , width:80,
				formatter:function (value,option,row) {
				var actions = [];
				actions.push('<a href="javascript:void(0);" onclick="vm.detailShow(' + row.outId + ');">查看</a>');
				return actions.join(' ');
				}
			},
		],
		viewrecords: true,
		height: 385,
		rowNum: 10,
		rowList : [25,50,100],
		rownumbers: true,
		rownumWidth: 25,
		autowidth:true,
		multiselect: false,
		pager: "#jqGridPager",
		jsonReader : {
			root: "page.list",
			page: "page.currPage",
			total: "page.totalPage",
			records: "page.totalCount",
			userdata: "userData"
		},
		prmNames : {
			page:"page",
			rows:"limit",
			order: "order"
		},
		gridComplete:function(){
			//隐藏grid底部滚动条
			$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
			var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
			vm.selectLists=userData.selectLists;

		}
	});
});

var vm = new Vue({
	el:'#rrapp',
	ssm: null,
	data:{
		showList: true,
		showListDetail: false,
		showDetail: true,
		title: null,
		page:{
			current:1, // 当前页
			size:10, // 分页数
			total:0, // 总条数
		},
		applyPage:{
			current:1, // 当前页
			size:15, // 分页数
			total:0, // 总条数
			tableData:[], //数据列
		},
		auditDialogVisible:false,   //  审核弹框
		e: {
			storeMaterialInTypeList: [
				{value: '1',label: '采购入库'},
				{value: '7',label: '调拨入库'},
				{value: '2',label: '红冲'}
			],
			storeMaterialOutTypeList: [
				{value: 6,label: '生产消耗'},
				{value: 8,label: '调拨出库'},
                // {value: 5,label: '盘亏'},
				{value: 4,label: '销售出库'}
			],
			taxEnum:[{value: 1,label: '含税'},{value: 0,label: '不含税'}],
			taxTypeList: [
				{value: 1,label: '是'},
				{value: 0,label: '否'},
			],
			applyPage:{
				current:1, // 当前页
				size:25, // 分页数
				total:0, // 总条数
				tableData:[], //数据列
			},
			materialUnitEnum : [
				{id: 0,describe: '个'},
				{id: 1,describe: 'm²'},
				{id: 2,describe: 'g'},
				{id: 3,describe: 'm'},
				{id: 4,describe: '张'},
			],
			whetherEnum:[],
			stockMaterialIoTypeEnum:[],

			directionEnum:[],
			storeMaterialOutInStatusEnum:[],
			financePaymentStatusEnum:[],
		},

		q:{
			outNo:null
		},
		storeMaterialForm: {
			storeMaterialInEntity: {},
			storeMaterialInDetailEntityList: [],
			unitMoney:''
		},
		auditOrRejectData: {
			id:null,
			operate:null,
			msg:"提示",
		},
		materialCategorySearch: '',
		materialCategoryList: [],
		defaultProps: {
			children: 'children',
			label: 'label'
		},
		purchaseApplyForm: {
			storePurchaseApplyEntity:{
				stockName: '',
				totalMoney: '',
				type: '',
				totalMD: '',
				tax: null,
				remark: null,
			},
			storePurchaseApplyDetailEntityList: []
		},
		storeMaterialOutType:{

			storestockmaterialIoEntity: []

		},
		materialSearchForm: {
			materialName: null
		},
		materialTableData: [],
		selectLists:[],
	},
	watch: {
		materialCategorySearch(val) {
			this.$refs.tree2.filter(val);
		}
	},
	methods: {
		// 库房出库查询
		query: function () {
			vm.reload();
		},
		addIn: function(){
			vm.showList = false;
			vm.showListDetail = true;
			vm.storePurchaseApply = {};
			vm.purchaseApplyForm = {
				storePurchaseApplyEntity:{
					type: '',
					totalMoney: '',
					tax: 1,
					remark: null,
				},
				storePurchaseApplyDetailEntityList: []
			}
			vm.addMaterialList = [];
			vm.materialTableData = [];
		},
		save: function (event) {
			$.ajax({
				type: "POST",
				url: baseURL + "storeMaterials/storematerialin/saveIn",
				contentType: "application/json",
				data: JSON.stringify(vm.storeMaterialForm),
				success: function(r){
					if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		onSubmit: function (event) {
			if(vm.CheckOutState()) {
				$.ajax({
					type: "POST",
					url: baseURL + "storeMaterials/storematerialinOut/save",
					contentType: "application/json",
					data: JSON.stringify(this.purchaseApplyForm),
					success: function (r) {
						if (r.code === 0) {
							alert('操作成功', function (index) {
								vm.close();
								vm.reload();
							});
						} else {
							alert(r.msg);
						}
					}
				});
			}else{
				alert("备注不能为空");
				return false;
			}
		},

		CheckOutState: function () {
			var ss = vm.purchaseApplyForm.storePurchaseApplyEntity.type;
			if(ss === 4){
				var strings = '';
				var remark = vm.purchaseApplyForm.storePurchaseApplyEntity.remark;
				if(remark == null){
					return false;
				}else if(strings === remark.trim()){
					return false;
				}
			}
			return true;
		},

		reset:function(){
			vm.q.outNo= '';
		},
		filterNode(value, data) {
			if (!value) return true;
			return data.label.indexOf(value) !== -1;
		},
        materialsSearchTwo(data){
            vm.page.current = 1;
            vm.materialsSearch(data);
        },
		materialsSearch(data) {
			if(typeof(data.id) != "undefined"){
				this.ssm = data.id;
			}
			var  paramData = {}
			if(typeof(data.id) == "undefined"){
				paramData.materialName =  this.materialSearchForm.materialName;
				paramData.categoryId = this.ssm;
			}else{
				paramData.categoryId = data.id;
				this.materialSearchForm.materialName = null;
			}
			var queryData = {page: this.page, params: paramData};
			//ajax 请求
			$.ajax({
				type: "POST",
				url: baseURL + "purchase/storepurchaseapply/queryMaterialsList",
				contentType: "application/json",
				data: JSON.stringify(queryData),
				success: function (r) {
					if (r.code == 0) {
						vm.page.size = r.page.size;
						vm.page.total = r.page.total;
						vm.materialTableData = r.page.records;
					} else {
						alert(r.msg);
					}
				}
			});
		},
		handleSizeChange(val) {
			vm.page.size = val;
			this.materialsSearch(val);
		},
		handleCurrentChange(val) {
			this.page.current = val
			this.materialsSearch(val);
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
				page:page,
				postData:{
					'outNo': vm.q.outNo,
				},
			}).trigger("reloadGrid");
		},
		searchInNo: function () {
			console.log(vm.storeMaterialForm.storeMaterialInEntity)

			if(vm.storeMaterialForm.storeMaterialInEntity.type == null){
				alert("请选择入库类型！")
			}else if(vm.storeMaterialForm.storeMaterialInEntity.inNo == null){
				alert("请输入单据号！")
			}
			var postData = {
				type: vm.storeMaterialForm.storeMaterialInEntity.type,
				inNo: vm.storeMaterialForm.storeMaterialInEntity.inNo
			};
			$.ajax({
				type: "POST",
				url: baseURL + "storeMaterials/storematerialin/queryInDetial",
				contentType: "application/json",
				data: JSON.stringify(postData),
				success: function(r){
					console.log(r)
					vm.storeMaterialForm.storeMaterialInDetailEntityList = r.materiallist;
				}
			});
		},
		/*格式化 单位*/
		formatUnit: function (row, column, cellValue, index) {
			for(var i=0; i<this.e.materialUnitEnum.length; i++){
				if(cellValue == this.e.materialUnitEnum[i].id){
					return this.e.materialUnitEnum[i].describe
				}
			}
		},
		addMaterial: function (row) {
			if(this.addMaterialList.indexOf(row.materialId)>=0){
				alert("耗材："+row.materialName+" 已添加！")
				return;
			}
			// 查询单价
			$.ajax({
				type: "GET",
				url: baseURL + "storeMaterials/storematerialinOut/getPrice/"+row.materialId,
				contentType: "application/json",
				success: function(r){
					if(r.price==null){
						alert("耗材："+row.materialName+" 未维护成本不能调出!");
						return;
					}
					vm.storeMaterialForm.unitMoney = r.price;
					var storePurchaseApplyDetail = {
						materialId:row.materialId,
						materialName:row.materialName,
						specifications:row.specifications,
						materialModel:row.materialModel,
						unitMoney:vm.storeMaterialForm.unitMoney,
						unit:row.showUnit,
						materialQuantity:1,
						totalMoney:vm.storeMaterialForm.unitMoney,
						stockName:vm.storeMaterialForm.stockName,
                        length:row.length,
                        width:row.width,
                        weight:row.weight
					}
					vm.purchaseApplyForm.storePurchaseApplyDetailEntityList.push(storePurchaseApplyDetail);
					vm.addMaterialList.push(row.materialId);
					if(vm.purchaseApplyForm.storePurchaseApplyDetailEntityList.length==1){
						vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = vm.storeMaterialForm.unitMoney
					}else{
						for(var i=1; i<vm.purchaseApplyForm.storePurchaseApplyDetailEntityList.length; i++){
							vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = Number(vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney)
								+ Number(vm.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].totalMoney);
						}
					}
				}
			});
		},
		/*移除采购列表耗材*/
		removePurchaseMaterials: function (row,index) {
			this.purchaseApplyForm.storePurchaseApplyDetailEntityList.splice(index,1)

			var materialIdIndex = vm.addMaterialList.indexOf(row.materialId);
			vm.addMaterialList.splice(materialIdIndex,1);
			vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = Number(vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney)
				- Number(row.totalMoney)
			this.changePurchaseTotal();
		},

		changePurchaseTotal: function () {
			vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = 0
			for(var i=0; i<this.purchaseApplyForm.storePurchaseApplyDetailEntityList.length; i++){
				vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney = Number(vm.purchaseApplyForm.storePurchaseApplyEntity.totalMoney)
					+ Number(vm.purchaseApplyForm.storePurchaseApplyDetailEntityList[i].totalMoney);
			}
		},
		/*分页数改变*/
		applySizeChange(val) {
			this.applyPage.size = val;
			this.purchaseApplySearch();
		},
		/*分页当前页改变改变*/
		applyCurrentChange(val) {
			this.applyPage.current = val
			this.purchaseApplySearch();
		},
		close: function (event) {
				vm.showList = true
				vm.showListDetail = false
				vm.showDetail = true
		},

		//价格计算
		totalMoneyChange: function (row,index) {
			var storePurchaseApplyDetail = this.purchaseApplyForm.storePurchaseApplyDetailEntityList[index];
			storePurchaseApplyDetail.totalMoney = percentNum(storePurchaseApplyDetail.unitMoney,storePurchaseApplyDetail.materialQuantity)
			this.purchaseApplyForm.storePurchaseApplyDetailEntityList.splice(index,1,storePurchaseApplyDetail);
			this.changePurchaseTotal();
		},

		// 获取明细
		getInfo: function (outId) {
			$.get(baseURL + "storeMaterials/storematerialinOut/info/" + outId, function (r) {
				vm.purchaseApplyForm.storePurchaseApplyEntity = r.infoData;
				vm.purchaseApplyForm.storePurchaseApplyEntity.stockName = r.stockName;
			});

			$.get(baseURL + "storeMaterials/storematerialinOut/storematerialinOutList/" + outId, function (r) {
				vm.purchaseApplyForm.storePurchaseApplyDetailEntityList = r.liststoreMaterialOutDetail;
			});
		},

		detailShow: function (outId) {
			this.showList = false;
			this.showDetail = false;
			vm.title = "出库详情"
			vm.getInfo(outId);
		},

	}
});

/**
 * 审核
 */
function auditOrReject() {
	console.log(vm.auditOrRejectData);
	var url = "storeMaterials/storematerialinOut/audit/"+vm.auditOrRejectData.id;
	if(vm.auditOrRejectData.operate == 0){
		url = "storeMaterials/storematerialinOut/reject/"+vm.auditOrRejectData.id;
	}
	$.get(baseURL + url, function(r){
		alert(r.msg);
		vm.reload();
	});
	vm.auditDialogVisible = false;
}


function percentNum(num,num2) {
	return ((num * num2).toFixed(2));
}